package com.leyou.item.services.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnums;
import com.leyou.common.exception.LyException;
import com.leyou.common.vo.PageResult;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import com.leyou.item.services.BrandService;
import com.leyou.item.services.CategoryService;
import com.leyou.item.services.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Date 2018/12/16  15:43
 * @Author JIE
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    /**
     * 商品分页查询
     * @param page
     * @param rows
     * @param saleable
     * @param key
     * @return
     */
    @Override
    public PageResult<Spu> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
        //分页
        PageHelper.startPage(page,rows);
        //过滤
        //创建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //搜索字段过滤
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("title","%"+key+"%");
        }
        //商品上下架过滤
        if (saleable!=null){
            criteria.andEqualTo("saleable",saleable);
        }
        //默认排序
        example.setOrderByClause("last_update_time DESC");
        //查询
        List<Spu> spuList = spuMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(spuList)){
            throw new LyException(ExceptionEnums.GOODS_NOT_FOND);
        }
        //解析分类和品牌的名称
        loadCategoryAndBrandName(spuList);

        //解析分页结果
        PageInfo<Spu> info = new PageInfo<>(spuList);
        return new PageResult<>(info.getTotal(),spuList);
    }

    /**
     * 商品的新增
     * @param spu
     */
    @Override
    @Transactional
    public void saveGoods(Spu spu) {
        //新增spu
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(new Date());
        spu.setId(null);
        spu.setSaleable(true);
        spu.setValid(false);
        int count = spuMapper.insert(spu);
        if(count!=1){
            throw new LyException(ExceptionEnums.GOODS_SAVE_ERROR);
        }
        //新增spu_detail
        SpuDetail spuDetail = spu.getSpuDetail();
        spuDetail.setSpuId(spu.getId());
        count = spuDetailMapper.insert(spuDetail);
        if(count!=1){
            throw new LyException(ExceptionEnums.GOODS_SAVE_ERROR);
        }
        saveSkuAndStock(spu);
     }
    /**
     * 查询SpuDetail
     * @param id
     * @return
     */
    @Override
    public SpuDetail queryDetailById(Long id) {
        SpuDetail spuDetail = spuDetailMapper.selectByPrimaryKey(id);
        if(spuDetail==null){
            throw new LyException(ExceptionEnums.GOODS_DETAIL_NOT_FOND);
        }
        return spuDetail;
    }

    /**
     * 根据spuid查询sku
     * @param spuId
     * @return
     */
    @Override
    public List<Sku> querySkuBySpuId(Long spuId) {
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        List<Sku> skuList = skuMapper.select(sku);
        if(CollectionUtils.isEmpty(skuList)){
            throw new LyException(ExceptionEnums.GOODS_SKU_NOT_FOND);
        }
        //查询库存
//        for (Sku s : skuList) {
//            Stock stock = stockMapper.selectByPrimaryKey(s.getId());
//            if(stock==null){
//                throw new LyException(ExceptionEnums.GOODS_STOCK_NOT_FOND);
//            }
//            s.setStock(stock.getStock());
//        }
        List<Long> ids = skuList.stream().map(Sku::getId).collect(Collectors.toList());
        List<Stock> stockList = stockMapper.selectByIdList(ids);
        if(CollectionUtils.isEmpty(skuList)){
                throw new LyException(ExceptionEnums.GOODS_STOCK_NOT_FOND);
        }
        Map<Long, Integer> stockMap = stockList.stream().collect(Collectors.toMap(Stock::getSkuId, Stock::getStock));
        skuList.forEach(s->s.setStock(stockMap.get(s.getId())));
        return skuList;
    }

    /**
     * 修改商品
     * @param spu
     */
    @Override
    @Transactional
    public void updateGoods(Spu spu) {
        //删除sku
        Sku sku = new Sku();
        sku.setSpuId(spu.getId());
        //查询sku
        List<Sku> skuList = skuMapper.select(sku);
        if(!CollectionUtils.isEmpty(skuList)){
            skuMapper.delete(sku);
            //删除stock
            List<Long> ids = skuList.stream().map(Sku::getId).collect(Collectors.toList());
            //批量删除
            stockMapper.deleteByIdList(ids);
        }

        //修改spu
        spu.setValid(null);
        spu.setSaleable(null);
        spu.setLastUpdateTime(new Date());
        spu.setCreateTime(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if(count!=1){
            throw new LyException(ExceptionEnums.GOODS_UPDATE_ERROR);
        }
        //修改detail
        count =spuDetailMapper.updateByPrimaryKeySelective(spu.getSpuDetail());
        if(count!=1){
            throw new LyException(ExceptionEnums.GOODS_UPDATE_ERROR);
        }
        //新增sku和stock
        saveSkuAndStock(spu);

    }

    @Override
    @Transactional
    public void deleteGoods(Long spuId) {
        //删除sku
        Sku sku = new Sku();
        sku.setSpuId(spuId);
        //查询sku
        List<Sku> skuList = skuMapper.select(sku);
        if(!CollectionUtils.isEmpty(skuList)){
            skuMapper.delete(sku);
            //删除stock
            List<Long> ids = skuList.stream().map(Sku::getId).collect(Collectors.toList());
            //批量删除
            stockMapper.deleteByIdList(ids);
        }
        //删除SpuDetail
        spuDetailMapper.deleteByPrimaryKey(spuId);
        //删除spu
        spuMapper.deleteByPrimaryKey(spuId);
    }

    /**
     * 商品下架
     * @param spuId
     */
    @Override
    public void unShelveGoods(Long spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(false);
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void putawayGoods(Long spuId) {
        Spu spu = new Spu();
        spu.setId(spuId);
        spu.setSaleable(true);
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 根据id查询spu
     * @param id
     * @return
     */
    @Override
    public Spu querySpuById(Long id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if(spu==null){
            throw new LyException(ExceptionEnums.GOODS_NOT_FOND);
        }
        //查询sku
        List<Sku> skuList = querySkuBySpuId(id);
        spu.setSkus(skuList);
        //查询detail
        SpuDetail spuDetail = queryDetailById(id);
        spu.setSpuDetail(spuDetail);
        return spu;
    }


    /**
     * 新增sku和stock的方法
     * @param spu
     */
    private void saveSkuAndStock(Spu spu){
     //定义库存的集合
        int count;
        List<Stock> stockList=new ArrayList<>();
        //新增sku
        List<Sku> skus = spu.getSkus();
        for (Sku sku : skus) {
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(new Date());
            sku.setSpuId(spu.getId());
            count = skuMapper.insert(sku);
            if(count!=1){
                throw new LyException(ExceptionEnums.GOODS_SAVE_ERROR);
            }
            Integer stockcount = sku.getStock();
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(stockcount);
            stockList.add(stock);
        }
        //批量新增stock
        count=stockMapper.insertList(stockList);
        if(count!=stockList.size()){
            throw new LyException(ExceptionEnums.GOODS_SAVE_ERROR);
        }
    }

    /**
     * 处理返回结果到页面中品牌名称和分类名称的方法
     *
     * @param spuList
     */
    private void loadCategoryAndBrandName(List<Spu> spuList) {
        for (Spu spu : spuList) {
            //处理分类名称
            List<String> names = categoryService.queryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()))
                    .stream().map(Category::getName).collect(Collectors.toList());
            spu.setCname(StringUtils.join(names,"/"));
            //处理品牌名称
            String bname = brandService.queryById(spu.getBrandId()).getName();
            spu.setBname(bname);
        }
    }
}
